#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "estructuras.h"
#include "constantes.h"
#include "sockets.h"
#include "NIPC.h"


int generarStructIPC(char *payload, short mode, InfoIPC* rInfoIPC)  
{	
	
	strcpy(rInfoIPC->descriptorID,GenerarDescriptor()); /*creo el descriptor y lo cargo en la estructura. */
	rInfoIPC->payLoadDescriptor=mode; /*cargo el protocolo a la struct*/
	rInfoIPC->payload = (char*) malloc(rInfoIPC->payLoadLength);
	memset(rInfoIPC->payload,'\0',rInfoIPC->payLoadLength);
	memcpy(rInfoIPC->payload, payload,rInfoIPC->payLoadLength); 
	

	return 0; 
}


char* GenerarDescriptor(){

	static char descriptor[16];
	char cadena [] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	int pos = 0;

 
	memset(descriptor, '\0', 16);

	for(pos = 0; pos < 15; descriptor[pos++] = cadena[(int)(rand()%62)]);
	descriptor[pos] = '\0';

	return descriptor;
}


int enviarIPC(int sock, InfoIPC *rInfoIPC)
{
	int tm;
	char *buffer;
	int bufLen;
	int length;

    bufLen = strlen(rInfoIPC->descriptorID) + 1 + sizeof(short) + sizeof(long) + sizeof(char)*rInfoIPC->payLoadLength; 
    buffer = (char*) malloc(bufLen);
    length = 0;
    memcpy(buffer,&(rInfoIPC->payLoadLength),sizeof(long));
    length = sizeof(long);
    memcpy(buffer + length, &(rInfoIPC->payLoadDescriptor), sizeof(short));
    length += sizeof(short);
    memcpy(buffer + length, rInfoIPC->descriptorID, strlen(rInfoIPC->descriptorID)+1);
    length += strlen(rInfoIPC->descriptorID)+1;
    memcpy(buffer + length, rInfoIPC->payload, rInfoIPC->payLoadLength);
    length +=  rInfoIPC->payLoadLength; 

	tm = send(sock,buffer,length,0);
	
	free(buffer);
	return tm;
}





int recibirIPC(int sock, InfoIPC* rInfoIPC)
{
	int length;
	int len;
	char* buffer;
	char* payload;
	int ret;
	int bRecibidos = 0;
	int bHastaAhora = 0;

	len = sizeof(short) + sizeof(long) + 16; 

	buffer	= (char*) malloc(len);

	ret = recv(sock, buffer, len, MSG_WAITALL);
	rInfoIPC->payLoadLength = 0;
	if(ret == len)
	{   
		length  = 0;
		memcpy(&rInfoIPC->payLoadLength, buffer, sizeof(long));
		length += sizeof(long);

		memcpy(&rInfoIPC->payLoadDescriptor, buffer + length, sizeof(short));
		length += sizeof(short);

		strncpy(rInfoIPC->descriptorID, buffer + length, 15);
		length += 16;
		
		free(buffer);
	}else 
		return -1; 
	
	
	if(rInfoIPC->payLoadLength > 0)
	{
		rInfoIPC->payload = (char*)malloc(rInfoIPC->payLoadLength);		

		bRecibidos=recv(sock, rInfoIPC->payload, rInfoIPC->payLoadLength, MSG_WAITALL);
		
		if (bRecibidos < rInfoIPC->payLoadLength) {
			printf("Error al recibir datos\n");
			return ERROR;
		}
		
		return 0; 
	
   }else return HANDSHAKE;	
}	








